﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.IO;
using System.Drawing;
using System.Globalization;

namespace Job.Web.Framework
{
    public class Functions
    {

        #region 字符串与二进制相互转换
        public static string ASCIIByteToString(byte[] characters)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();
            string constructedString = encoding.GetString(characters);
            return (constructedString);
        }
        //  byte[]   bytes   =   System.Text.Encoding.ASCII.GetBytes(str);
        //byte[]   b   =   System.Text.Encoding.Default.GetBytes(string   s);   

        public static string UnicodeByteToString(byte[] characters)
        {
            UnicodeEncoding encoding = new UnicodeEncoding();
            string constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        public static byte[] StringToByteArray(string fromStr)
        {
            System.Text.UTF8Encoding n = new UTF8Encoding();
            byte[] result = n.GetBytes(fromStr);
            return result;
        }

        public static string ByteArrayToString(byte[] frombyte)
        {
            string result = "";
            System.IO.Stream fileStream = new System.IO.MemoryStream(frombyte);

            using (StreamReader reader = new StreamReader(fileStream))
            {
                result = reader.ReadToEnd();
            }

            return result;
        }

        public static Stream ByteArrayToStream(byte[] frombyte)
        {
            System.IO.Stream fileStream = new System.IO.MemoryStream(frombyte);
            return fileStream;
        }

        public static byte[] StreamToByteArray(Stream fromStream)
        {
            byte[] result = null;
            if (fromStream.CanSeek)
            {
                fromStream.Seek(0, System.IO.SeekOrigin.Begin);
            }

            result = new byte[fromStream.Length];
            fromStream.Read(result, 0, result.Length);
            return result;
        }

        #endregion
        /// <summary>
        /// 字符串转成数组
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="spstr"></param>
        /// <returns></returns>
        public static string[] StringToList(string expression, string spstr)
        {
            string[] result;
            result = expression.Split(new char[] { Convert.ToChar(spstr) });
            return result;
        }

        /// <summary>
        /// 按字节数获取字符串，中文算两个字节
        /// </summary>
        /// <param name="strSrc"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static string GetStrByByteCount(string strSrc, int count)
        {
            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            char[] stringChar = strSrc.ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;
            bool isCut = false;
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    sb.Append(stringChar[i]);
                    nLength += 2;
                }
                else
                {
                    sb.Append(stringChar[i]);
                    nLength = nLength + 1;
                }

                if (nLength > count)
                {
                    isCut = true;
                    break;
                }
            }
            if (isCut)
                return sb.ToString() + "...";
            else
                return sb.ToString();
        }

        #region -- Html编码解码 --
        public static string HtmlEncode(string str)
        {
            if (str != null)
            {
                str = str.Replace("<", "&lt;");
                str = str.Replace(">", "&gt;");
                str = str.Replace("  ", " &nbsp;");
                //s_str = s_str.Replace("'","&#39;");
                str = str.Replace("\r\n", "<br>");
            }
            return str;
        }



        public static string HtmlDecode(string str)
        {
            if (str != null)
            {
                str = str.Replace("&nbsp;", " ");
                str = str.Replace("<br>", "\r\n");
                str = str.Replace("&lt;", "<");
                str = str.Replace("&gt;", ">");
                //s_str = s_str.Replace("&#39;","'");
            }

            return str;
        }

        /// <summary>
        /// 用于不需要对多文本输入框html编码，但需要对其进行换行处理时
        /// </summary>
        /// <param name="str">要处理的字符串</param>
        /// <returns>替换后的返回值 </returns>
        public static string TextAreaEncode(string str)
        {
            if (str != null)
            {
                str = str.Replace("  ", " &nbsp;");
                str = str.Replace("\r\n", "<br>");
            }
            return str;
        }

        /// <summary>
        /// 用于不需要对多文本输入框html编码，但需要对其进行换行处理时
        /// </summary>
        /// <param name="str">要处理的字符串</param>
        /// <returns>替换后的返回值 </returns>
        public static string TextAreaDecode(string str)
        {
            if (str != null)
            {
                str = str.Replace("&nbsp;", "  ");
                str = str.Replace("<br>", "\r\n");
                str = str.Replace("<BR>", "\r\n");
            }
            return str;
        }

        #endregion

        #region -- 加密解密 --


        /// <summary> 
        /// Encrypt the string 
        /// Attention:key must be 8 bits 
        /// </summary> 
        /// <param name="strText">string</param> 
        /// <param name="strEncrKey">key</param> 
        /// <returns></returns> 
        public static string DesEncrypt(string strText, string strEncrKey)
        {
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            try
            {
                byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());


            }
            catch (Exception error)
            {
                return "error:" + error.Message + "\r";
            }
        }

        /// <summary> 
        /// Decrypt string 
        /// Attention:key must be 8 bits 
        /// </summary> 
        /// <param name="strText">Decrypt string</param> 
        /// <param name="sDecrKey">key</param> 
        /// <returns>output string</returns> 
        public static string DesDecrypt(string strText, string sDecrKey)
        {
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            byte[] inputByteArray = new Byte[strText.Length];
            try
            {
                byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                Encoding encoding = new UTF8Encoding();
                return encoding.GetString(ms.ToArray());
            }
            catch (Exception error)
            {
                return "error:" + error.Message + "\r";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="PasswordString"></param>
        /// <returns></returns>
        public static string EncryptPassword(string PasswordString)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(PasswordString, "MD5");
        }
        #endregion

        #region -- 危险字符过滤 - -
        /// <summary>
        /// --2007/5/10--zjb--
        /// </summary>
        /// <param name="inputString"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>

        public static string InputText(string inputString, int maxLength)
        { //过滤JAVA脚本和html 
            System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[/s/S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[/s/S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[/s/S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[/s/S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[/s/S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            inputString = regex1.Replace(inputString, ""); //过滤<script></script>标记  
            inputString = regex2.Replace(inputString, ""); //过滤href="/u/javascript: ";(<A>) 属性  
            inputString = regex3.Replace(inputString, " _disibledevent="); //过滤其它控件的on...事件  
            inputString = regex4.Replace(inputString, ""); //过滤iframe  
            inputString = regex5.Replace(inputString, ""); //过滤frameset  
            //过滤危险字符。。。。 
            StringBuilder retVal = new StringBuilder();
            if ((inputString != null) && (inputString != String.Empty))
            {
                inputString = inputString.Trim();
                if (inputString.Length > maxLength)
                {
                    inputString = inputString.Substring(0, maxLength);
                }
                for (int i = 0; i < inputString.Length; i++)
                {
                    switch (inputString[i])
                    {
                        case '%':
                            retVal.Append("");
                            break;
                        case '/':
                            retVal.Append("");
                            break;
                        case '*':
                            retVal.Append("");
                            break;
                        case '-':
                            retVal.Append("");
                            break;
                        case '"':
                            retVal.Append("&quot;");
                            break;
                        case '<':
                            retVal.Append("&lt;");
                            break;
                        case '>':
                            retVal.Append("&gt;");
                            break;
                        default:
                            retVal.Append(inputString[i]);
                            break;
                    }
                }

                // Replace single quotes with white space 
                retVal.Replace("'", " ");
            }
            return retVal.ToString();
        }
        #endregion

        #region 缩略图
        /**/
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>    
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            Image originalImage = Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）  
                    if (ow >= oh)
                    {
                        toheight = originalImage.Height * width / originalImage.Width;
                    }
                    else
                    {
                        towidth = originalImage.Width * height / originalImage.Height;
                    }
                    break;
                case "W"://指定宽，高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        #endregion

        #region 日期与字符串的转换
        /**/
        /// <summary>
        /// 将日期转换为字符串显示
        /// </summary>
        /// <param name="value">需要转换为字符串的日期</param>
        public static string GetDateStr(DateTime value)
        {
            if (null == value) return "";
            return value.ToString("yyyy-MM-dd");
        }
        /// <summary>
        /// 将日期时间转换为字符串显示
        /// </summary>
        /// <param name="value">需要转换为字符串的日期</param>
        public static string GetDateTimeStr(DateTime value)
        {
            if (null == value) return "";
            return value.ToString("yyyy-MM-dd HH:mm:ss");
        }

        /// <summary>
        /// 将字符串转换为日期
        /// </summary>
        /// <param name="str">需要转换为日期的字符串</param>
        public static DateTime GetDateTime(string str)
        {
            //if (str == null || str.Trim().Length == 0) return null;
            //try
            //{
                CultureInfo culture = new CultureInfo("zh-CN");
            //    //DateTime date = DateTime.ParseExact(tbValidate.Text.Trim(), "yyyy-MM-dd", culture);
            //    //if ( null != date )  return date;

            //    //DateTime date = DateTime.ParseExact(tbValidate.Text.Trim(), "yy-MM-dd", culture);
            //    //if (null != date) return date;
                DateTime date;

                date = DateTime.ParseExact(str.Trim(), "yyyy-M-d", culture);
                if (null != date) return date;

                date = DateTime.ParseExact(str.Trim(), "yy-M-d", culture);
                if (null != date) return date;

                throw new Exception("无法转换为日期");

            //}
            //catch (Exception e)
            //{
            //    return null;
            //}
        }


                    

        #endregion
    }
}
